package cn.cn77.futures.utils;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Utils {

	/**
	 * 验证是否是手机号码
	 * 
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		System.out.println(m.matches() + "---");
		return m.matches();
	}

	/**
	 * MD5加密
	 * 
	 * @param str
	 * @return
	 */
	public static String MD5(String str) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		char[] charArray = str.toCharArray();
		byte[] byteArray = new byte[charArray.length];
		for (int i = 0; i < charArray.length; i++) {
			byteArray[i] = (byte) charArray[i];
		}
		byte[] md5Bytes = md5.digest(byteArray);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}

	/**
	 * 加密密码
	 * 
	 * @param phone
	 * @param password
	 * @return
	 */
	public static String encodePassword(String password) {
		return MD5(password);
	}

	/**
	 * postCode获取方法
	 * 
	 * @param
	 * @param timeStamp
	 * @return
	 */
	public static String postCode(String id, String timeStamp) {
		return MD5("qh") + MD5(id) + MD5(timeStamp);
	}

	/**
	 * 将JSON数组转换为ArrayList
	 * 
	 * @param field
	 *            解析数组需要的字段
	 * @param jArr
	 *            JSON数组
	 * @return list集合
	 * @throws JSONException
	 *             JSON数据类型异常
	 */
	public static ArrayList<HashMap<String, String>> parseJSONArray(
			String[] field, JSONArray jArr) throws JSONException {
		ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
		HashMap<String, String> map;
		JSONObject o;
		for (int index = 0; index < data.size(); index++) {
			map = new HashMap<String, String>();
			o = jArr.getJSONObject(index);
			for (int m = 0; m < field.length; m++) {
				map.put(field[m], o.getString(field[m]));
			}
			data.add(map);
		}
		return data;
	}

	/**
	 * 获取当前时间的字符串格式
	 * 
	 * @return
	 */
	public static String getCurrentTime(String timeFormat) {
		SimpleDateFormat formatter = new SimpleDateFormat(timeFormat);
		Date currentTime = new Date();
		return formatter.format(currentTime);
	}
}
